package zhu;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class StudentManagementDialogs {

    private static final String URL = "jdbc:mysql://localhost:3306/exam_management_system";
    private static final String USER = "root";
    private static final String PASSWORD = "zhu751111";

    public void openAddStudentDialog(JFrame parent) {
        JTextField studentIdField = new JTextField(10);
        JTextField nameField = new JTextField(10);
        JPasswordField passwordField = new JPasswordField(10);
        JPasswordField confirmPasswordField = new JPasswordField(10);
        JTextField secretQuestionField = new JTextField(10);
        JPasswordField secretAnswerField = new JPasswordField(10);
        JComboBox<String> roleComboBox = new JComboBox<>(new String[]{"学生", "管理员"});
        JPanel panel = new JPanel(new GridLayout(0, 2));
        panel.add(new JLabel("学号："));
        panel.add(studentIdField);
        panel.add(new JLabel("姓名："));
        panel.add(nameField);
        panel.add(new JLabel("密码："));
        panel.add(passwordField);
        panel.add(new JLabel("确认密码："));
        panel.add(confirmPasswordField);
        panel.add(new JLabel("密保问题："));
        panel.add(secretQuestionField);
        panel.add(new JLabel("密保答案："));
        panel.add(secretAnswerField);
        panel.add(new JLabel("角色："));
        panel.add(roleComboBox);

        int result = JOptionPane.showConfirmDialog(parent, panel, "添加学生", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            String studentId = studentIdField.getText();
            String name = nameField.getText();
            String password = new String(passwordField.getPassword());
            String confirmPassword = new String(confirmPasswordField.getPassword());
            String secretQuestion = secretQuestionField.getText();
            String secretAnswer = new String(secretAnswerField.getPassword());
            String role = (String) roleComboBox.getSelectedItem();
            if (studentId.isEmpty() || name.isEmpty() || password.isEmpty() || confirmPassword.isEmpty() || secretQuestion.isEmpty() || secretAnswer.isEmpty() || role.isEmpty()) {
                JOptionPane.showMessageDialog(parent, "所有字段都是必填项！");
                return;
            }
            if (!password.equals(confirmPassword)) {
                JOptionPane.showMessageDialog(parent, "密码不匹配！");
                return;
            }
            try {
                addStudentToDatabase(studentId, name, password, role, secretQuestion, secretAnswer);
                JOptionPane.showMessageDialog(parent, "学生添加成功！");
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(parent, "添加学生到数据库时出错：" + e.getMessage());
            }
        }
    }

    private void addStudentToDatabase(String studentId, String name, String password, String role, String secretQuestion, String secretAnswer) throws SQLException {
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement("INSERT INTO users (student_id, name, password, role, secret_question, secret_answer) VALUES (?, ?, ?, ?, ?, ?)")) {
            pstmt.setString(1, studentId);
            pstmt.setString(2, name);
            pstmt.setString(3, password);
            pstmt.setString(4, role);
            pstmt.setString(5, secretQuestion);
            pstmt.setString(6, secretAnswer);
            pstmt.executeUpdate();
        }
    }

    public void openDeleteStudentDialog(JFrame parent) {
        JTextField studentIdField = new JTextField(10);
        JPanel panel = new JPanel();
        panel.add(new JLabel("输入要删除的学生学号："));
        panel.add(studentIdField);

        int result = JOptionPane.showConfirmDialog(parent, panel, "删除学生", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            String studentId = studentIdField.getText();
            if (studentId.isEmpty()) {
                JOptionPane.showMessageDialog(parent, "学号不能为空！");
                return;
            }
            try {
                int deletedRows = deleteStudentFromDatabase(studentId);
                if (deletedRows > 0) {
                    JOptionPane.showMessageDialog(parent, "学生删除成功！");
                } else {
                    JOptionPane.showMessageDialog(parent, "没有找到学号为 " + studentId + " 的学生。");
                }
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(parent, "删除学生时出错：" + e.getMessage());
            }
        }
    }

    private int deleteStudentFromDatabase(String studentId) throws SQLException {
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement("DELETE FROM users WHERE student_id = ?")) {
            pstmt.setString(1, studentId);
            return pstmt.executeUpdate();
        }
    }

    public void openModifyStudentDialog(JFrame parent) {
        JTextField studentIdField = new JTextField(10);
        JTextField nameField = new JTextField(10);
        JPasswordField passwordField = new JPasswordField(10);
        JPasswordField confirmPasswordField = new JPasswordField(10);
        JTextField secretQuestionField = new JTextField(10);
        JPasswordField secretAnswerField = new JPasswordField(10);
        JComboBox<String> roleComboBox = new JComboBox<>(new String[]{"学生", "管理员"});
        JPanel panel = new JPanel(new GridLayout(0, 2));
        panel.add(new JLabel("学号："));
        panel.add(studentIdField);
        panel.add(new JLabel("新姓名："));
        panel.add(nameField);
        panel.add(new JLabel("新密码："));
        panel.add(passwordField);
        panel.add(new JLabel("确认新密码："));
        panel.add(confirmPasswordField);
        panel.add(new JLabel("新密保问题："));
        panel.add(secretQuestionField);
        panel.add(new JLabel("新密保答案："));
        panel.add(secretAnswerField);
        panel.add(new JLabel("新角色："));
        panel.add(roleComboBox);

        int result = JOptionPane.showConfirmDialog(parent, panel, "修改学生", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            String studentId = studentIdField.getText();
            String name = nameField.getText();
            String password = new String(passwordField.getPassword());
            String confirmPassword = new String(confirmPasswordField.getPassword());
            String secretQuestion = secretQuestionField.getText();
            String secretAnswer = new String(secretAnswerField.getPassword());
            String role = (String) roleComboBox.getSelectedItem();
            if (studentId.isEmpty() || name.isEmpty() || password.isEmpty() || confirmPassword.isEmpty() || secretQuestion.isEmpty() || secretAnswer.isEmpty() || role.isEmpty()) {
                JOptionPane.showMessageDialog(parent, "所有字段都是必填项！");
                return;
            }
            if (!password.equals(confirmPassword)) {
                JOptionPane.showMessageDialog(parent, "密码不匹配！");
                return;
            }
            try {
                modifyStudentInDatabase(studentId, name, password, role, secretQuestion, secretAnswer);
                JOptionPane.showMessageDialog(parent, "学生修改成功！");
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(parent, "在数据库中更新学生信息时出错：" + e.getMessage());
            }
        }
    }

    private void modifyStudentInDatabase(String studentId, String name, String password, String role, String secretQuestion, String secretAnswer) throws SQLException {
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement("UPDATE users SET name = ?, password = ?, role = ?, secret_question = ?, secret_answer = ? WHERE student_id = ?")) {
            pstmt.setString(1, name);
            pstmt.setString(2, password);
            pstmt.setString(3, role);
            pstmt.setString(4, secretQuestion);
            pstmt.setString(5, secretAnswer);
            pstmt.setString(6, studentId);
            int rowsUpdated = pstmt.executeUpdate();
            if (rowsUpdated > 0) {
                JOptionPane.showMessageDialog(null, "学生信息更新成功！");
            } else {
                JOptionPane.showMessageDialog(null, "没有找到符合条件的学生。");
            }
        }
    }

    public void openQueryStudentDialog(JFrame parent) {
        JTextField searchField = new JTextField(10);
        JPanel panel = new JPanel();
        panel.add(new JLabel("输入学号或姓名关键字："));
        panel.add(searchField);

        int result = JOptionPane.showConfirmDialog(parent, panel, "查找学生", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            String searchQuery = searchField.getText();
            if (searchQuery.isEmpty()) {
                JOptionPane.showMessageDialog(parent, "搜索内容不能为空！");
                return;
            }
            queryStudents(searchQuery);
        }
    }

    private void queryStudents(String searchQuery) {
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(
                     "SELECT * FROM users WHERE student_id LIKE ? OR name LIKE ?")) {
            pstmt.setString(1, "%" + searchQuery + "%");
            pstmt.setString(2, "%" + searchQuery + "%");
            ResultSet rs = pstmt.executeQuery();
            StringBuilder results = new StringBuilder();
            while (rs.next()) {
                String studentId = rs.getString("student_id");
                String name = rs.getString("name");
                String role = rs.getString("role");
                results.append("学号: ").append(studentId)
                        .append(", 姓名: ").append(name)
                        .append(", 角色: ").append(role)
                        .append("\n");
            }
            if (results.length() > 0) {
                JOptionPane.showMessageDialog(null, "找到以下学生信息：\n" + results.toString());
            } else {
                JOptionPane.showMessageDialog(null, "没有找到符合条件的学生。");
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "在数据库中搜索学生时出错：" + e.getMessage());
        }
    }
}

